package character;

import item.WeaponFactory;
import item.Weapon;
import item.Item;
import item.WeaponEnum;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CharacterInventory {
    protected MyCharacter owner;
    protected Map<Item, Item> items = new HashMap<Item, Item>();
    protected Weapon equippedWeapon;

    @Deprecated
    protected CharacterInventory() {}
    
    public CharacterInventory(MyCharacter owner) {
        this.owner = owner;
        equippedWeapon = WeaponFactory.getWeapon(owner, WeaponEnum.FIST);
    }

    public List<Item> getItems() {
	return new ArrayList<Item>(items.values());
    }

    public void addItem(Item item) {
        item.setOwner(owner);
	if(items.containsKey(item)) {
	    items.get(item).changeQuantity(item.getQuantity());
	} else {
	    items.put(item ,item);
	}
        if(item instanceof Weapon) {
            equippedWeapon = (Weapon)item;
            System.out.println("Equipped "+item);
        }
    }

    public void addItems(List<Item> items) {
	for(Item item : items)
	    addItem(item);
    }

    /**
     * Removes and returns as many of the given item (with quantity) as possible. If not in the map, returns null.
     */
    public Item popItemWithQuantity(Item itemToPop) {
	if(items.containsKey(itemToPop)) {
            Item itemInMap = items.get(itemToPop);
            if(itemInMap.getQuantity() > itemToPop.getQuantity()) {
                itemInMap.changeQuantity(-itemToPop.getQuantity());
                return itemToPop.clone();
            } else {
                Item savedItem = itemInMap.clone();
                items.remove(itemToPop);
                return savedItem;
            }
	} else {
	    return null;
	}
    }

    public void clear() {
	items.clear();
    }
    
    public boolean containsItemWithoutQuantity(Item item) {
        return items.containsKey(item);
    }

    public boolean containsItemWithQuantity(Item item) {
	if(items.containsKey(item) && items.get(item).getQuantity() >= item.getQuantity())
	    return true;
	else
	    return false;
    }

    public Weapon getEquippedWeapon() {
        return equippedWeapon;
    }
    public void setEquippedWeapon(Weapon equippedWeapon) {
        if(equippedWeapon == null)
            removeEquippedWeapon();
        else
            this.equippedWeapon = equippedWeapon;
    }
    public void removeEquippedWeapon() {
        equippedWeapon = WeaponFactory.getWeapon(owner, WeaponEnum.FIST);
    }
}
